#include <network.h>

#include <pthread.h>

#define MAX_DATA 200

typedef struct _DataBase
{
	char name[50];
	char path[1000];
}DataBase;

DataBase db[MAX_DATA];

int get_plugin_on_wowace(char *plugin)
{
	char temp[200], *result, *ptr_start, *ptr_end;

	if(!plugin)
		return -1;

	sprintf(temp, "/addons/%s/", plugin);

	// First Stage
	result = get_page("www.wowace.com", temp);

	if( !result || strncmp(result, "HTTP/1.1 200 OK", 15) ) //HTTP/1.1 307 TEMPORARY REDIRECT
		return -1;

	if( (ptr_start=strstr(result, "<dt>Recent files</dt>")) == NULL )
		return -1;

	if( (ptr_start=strstr(ptr_start, "<a href=\"/addons/")) == NULL )
		return -1;

	ptr_start += 9;

	if( (ptr_end=strstr(ptr_start, "\"")) == NULL )
		return -1;

	memcpy(&temp[0], ptr_start, ptr_end-ptr_start);
	temp[ptr_end-ptr_start] = '\0';

	// Second Stage
	result = get_page("www.wowace.com", temp);

	if( !result || strncmp(result, "HTTP/1.1 200 OK", 15) ) //HTTP/1.1 307 TEMPORARY REDIRECT
		return -1;

	if( (ptr_start=strstr(result, "<li class=\"user-action user-action-download\"><span><a href=\"")) == NULL )
		return -1;

	ptr_start += 60;

	if( (ptr_end=strstr(ptr_start, "\">Download</a></span></li>")) == NULL )
		return -1;

	memcpy(&temp[0], ptr_start, ptr_end-ptr_start);
	temp[ptr_end-ptr_start] = '\0';

	printf("%s\n", temp);

	return 0;
}


int main(int argc, char *argv[])
{
	pthread_t pth[MAX_DATA];
	int i;

	bzero(&db, sizeof(db));

	for(i=1; i<argc; i++)
		sprintf(db[i-1].name, argv[i]);


	for(i=0; db[i].name[0]!=0; i++)
		pthread_create(&pth[i], NULL, (void *)&get_plugin_on_wowace, db[i].name);
	for(i=0; db[i].name[0]!=0; i++)
		pthread_join(pth[i], NULL);

	return 0;
}
